import React, { useEffect, useState } from 'react';
import { Button, Space, Table, Tag } from 'antd';
import type { TableProps } from 'antd';
import http from '../../api/http';
import type { FormProps } from 'antd';
import { Checkbox, Form, Input } from 'antd';

type FieldType = {
  title?: string;
  tag?: string;
  age?: number;
};


interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

const App: React.FC = () => {

  // 定义数据
  const [data, setData] = useState([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [form] = Form.useForm();
  const [title,setTitle] = useState('')
  const [tag,setTag] = useState('')

  // 获取表格数据
  const fetchData = async () => {
    const params: {
      page: number,
      pageSize: number,
      keyword?: string,//搜索标题
      tag?: string
    } = {
      page,
      pageSize
    }
    if(title) params.keyword = title;
    if(tag) params.tag = tag;
    const res = await http.get('/article/list', {
      params
    })
    console.log(res, '表格数据')
    const { rows, count } = res.data;
    setData(rows)
    setTotal(count)
  }

  // 回调请求函数
  useEffect(() => {
    fetchData()
  }, [page, pageSize,title,tag])

  // 分页
  const change = (page: number, pageSize: number) => {
    setPage(page)
    setPageSize(pageSize)
  }

  // 搜索
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    setTitle(values.title)
    setTag(values.tag)
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 重置
  const handleReact = () => {
    setTag('')
    setTitle('')
    form.resetFields()
  }

  // 渲染
  const columns: TableProps<DataType>['columns'] = [
    {
      title: '用户名',
      dataIndex: 'title',
      key: 'title',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '性别',
      dataIndex: '男',
      key: '男',
    },
    {
      title: '年龄',
      dataIndex: 'viewCount',
      key: 'viewCount',
    },
    {
      title: '邮箱',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '地址',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '分类',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.name.length > 5 ? 'geekblue' : 'green';
            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button color='purple' variant="filled">
            查看
          </Button>
          <Button color='blue' variant="filled">
            查看
          </Button>
          <Button color='red' variant="filled">
            查看
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 搜索表单 */}
      <Form
        name="basic"
        layout='inline'
        form={form}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 1600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="用户名"
          name="title"
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="类别"
          name="tag"
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="年龄"
          name="age"
        >
          <Input />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>

        <Form.Item label={null}>
          <Button type='default' onClick={() => handleReact()}>
            重置
          </Button>
        </Form.Item>

      </Form>

      {/* 表格 */}
      <Table<DataType>
        columns={columns}
        dataSource={data}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共有 ${total} 条`,
          onChange: change
        }}
      />
    </div>
  )
};

export default App;